package com.joint.web.action.main;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.dao.jdbc.JdbcDao;
import com.fz.us.base.util.CommonUtil;
import com.fz.us.base.util.DataUtil;
import com.joint.base.entity.Company;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Users;
import com.joint.base.entity.system.Admin;
import com.joint.base.service.AdminService;
import com.joint.base.service.CompanyService;
import com.joint.base.service.UsersService;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * 后台Action类 - 
 * ============================================================================
 * 版权所有 2013 min_xu。
 * ----------------------------------------------------------------------------
 * 
 * @author min_xu
 * 
 * @version 0.1 2013-7-15
 */

@ParentPackage("main")
public class AjaxUsersAction extends BaseAdminAction {
	private static final long serialVersionUID = -5383463207248344967L;
	
	@Resource
	private UsersService usersService;
	@Resource
	private AdminService adminService;
	@Resource
	private CompanyService companyService;
	@Resource
	private JdbcDao jdbcDao;
	
	private List<Map<String,String>> listMap;
	private List<Users> list;
	private String type;
	private String _;//实时刷新
	
	
	//jqgrid params
	private String name;
	private String username;
	private String usermobile;
	private Users user;
	private File filedata;
	private FileManage fileManage;
	private String fileId;
	private String filename;
	private String filedataFileName;
	private String filedataContentType;

	//jqGrid
	public String jqGrid(){
		pager = new Pager();
		pager.setPageSize(rows);
		pager.setPageNumber(page);
		pager.setOrderBy("createDate");
		pager.setOrderType(BaseEnum.OrderType.desc);
		
		List<JSONObject> dataRows = new ArrayList<JSONObject>();
		Map<String, Object> data = new HashMap<String, Object>(); 
		

		Map<String,Object> params = new HashMap<String,Object>();
		params.put("username", username);
		params.put("usermobile", usermobile);

		pager = adminService.findByPager(pager,params,sidx, BaseEnum.OrderType.valueOf(sord));

			List<Admin> listAdmin = (List<Admin>) pager.getList();
			for(Admin a:listAdmin){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", StringUtils.isNotEmpty(a.getId())?a.getId():"");
				map.put("username", a.getUsername());
				map.put("usermobile", CommonUtil.isMobile(a.getUsername())?a.getUsername():a.getUsermobile());
				map.put("expireDate",a.getExpireDate() ==null?"": DataUtil.DateToString(a.getExpireDate()));
				map.put("openId", StringUtils.isEmpty(a.getOpenId())?"否":"是");
				map.put("createDate", DataUtil.DateToString(a.getCreateDate()));

				Users users =usersService.getByAdmin(a);
				if(null != users){
					map.put("uid", StringUtils.isNotEmpty(users.getId())?users.getId():"");
					map.put("name", StringUtils.isNotEmpty(users.getName())?users.getName():"");
					map.put("pinYinHead", StringUtils.isNotEmpty(users.getPinYinHead())?users.getPinYinHead():"");
					map.put("pinYin", StringUtils.isNotEmpty(users.getPinYin())?users.getPinYin():"");

					if(users.getCompany()!=null){
						Company company = users.getCompany();
						map.put("companyId", company.getId());
						map.put("companyName", company.getName());
						map.put("companySubName", company.getSubname());
					}else{
						map.put("companyId", "");
						map.put("companyName", "");
						map.put("companySubName", "");
					}
				}
				dataRows.add(JSONObject.fromObject(map));
			}
			total = pager.getPageCount();

	    data.put("dataRows", JSONArray.fromObject(dataRows));
	    data.put("records", pager.getTotalCount());
	    data.put("page",page);
	    data.put("rows",rows);
	    data.put("total",total);
		
	    return ajaxJson(JSONObject.fromObject(data).toString());
	}
	
	public String list(){
		if(page == 0){
			page = 1;
		}
		pager = new Pager();
		pager.setPageSize(LISTVIEW_MP_SIZE);
		pager.setPageNumber(page);
		
		pager = usersService.findByPagerAndCompany(pager, null,null, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
		list = (List<Users>) pager.getList();
		
		return "list";
	}
	
	/**
	 * 
#SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount FROM ss_company WHERE createDate > '2014-01-01' and state='Enable' GROUP BY date_format(createDate, '%Y-%m-%d') 
#过去的12个月的按月算
#SELECT date_format(createDate, '%Y-%m') as perDate,count(*) as perCount FROM ss_users WHERE createDate > '2014-01' and state='Enable' GROUP BY date_format(createDate, '%Y-%m') 

#之前的用户数 + 当天=总计
SELECT count(*) as perCount FROM ss_users WHERE createDate <= '2014-01' and state='Enable'

参数，数字，周期（30,天）一个月的默认 （12,月）一年的
	 * */
	public String chart(){
		if (StringUtils.isEmpty(type)) {
			type = "month";//year //month
		}
		String dateS = "";
		Date curDate = new Date();
		int i = 0;
		Map<String, Object> pmap = new HashMap<String, Object>();
		Map<String, Object> cmap = new HashMap<String, Object>();
		Map<String, Object> tpmap = new HashMap<String, Object>();
		Map<String, Object> tcmap = new HashMap<String, Object>();
		
		//定义输出的四组数据
		List<Long> pdata = new ArrayList<Long>();
		List<Long> cdata = new ArrayList<Long>();
		List<Long> tpdata = new ArrayList<Long>();
		List<Long> tcdata = new ArrayList<Long>();
		List<String> ndata = new ArrayList<String>();
		
		String psql = "";
		String csql = "";
		String tpsql = "";
		String tcsql = "";
		
		if(type.equals("month")){
			dateS = DataUtil.DateToString(
                    DataUtil.getAfterDay(curDate, -29), "yyyy-MM-dd");
			
			for ( i = 0; i < 30; i++) {
				String yearMonth = DataUtil.DateToString(
                        DataUtil.getAfterDay(curDate, i - 29), "yyyy-MM-dd");
				
				pmap.put(yearMonth, new Long(0));
				cmap.put(yearMonth, new Long(0));
				tpmap.put(yearMonth, new Long(0));
				tcmap.put(yearMonth, new Long(0));
				
				ndata.add(yearMonth);
			}
			psql = "SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount FROM sys_admin WHERE createDate > :date GROUP BY date_format(createDate, '%Y-%m-%d') ";
			csql = "SELECT date_format(createDate, '%Y-%m-%d') as perDate,count(*) as perCount FROM sys_company WHERE createDate > :date and state='Enable' GROUP BY date_format(createDate, '%Y-%m-%d')";
			tpsql = "SELECT count(*) as perCount FROM sys_admin WHERE createDate < :date ";
			tcsql = "SELECT count(*) as perCount FROM sys_company WHERE createDate < :date and state='Enable'";
			
		}else{
			dateS = DataUtil.DateToString(
                    DataUtil.getAfterMonths(curDate, -11), "yyyy-MM");
			dateS += "-01";
			
			for ( i = 0; i < 12; i++) {
				String yearMonth = DataUtil.DateToString(
                        DataUtil.getAfterMonths(curDate, i - 11), "yyyy-MM");
				
				pmap.put(yearMonth, new Long(0));
				cmap.put(yearMonth, new Long(0));
				tpmap.put(yearMonth, new Long(0));
				tcmap.put(yearMonth, new Long(0));
				
				ndata.add(yearMonth);
			}
			psql = "SELECT date_format(createDate, '%Y-%m') as perDate,count(*) as perCount FROM sys_admin WHERE createDate > :date  GROUP BY date_format(createDate, '%Y-%m') ";
			csql = "SELECT date_format(createDate, '%Y-%m') as perDate,count(*) as perCount FROM sys_company WHERE createDate > :date and state='Enable' GROUP BY date_format(createDate, '%Y-%m')";
			tpsql = "SELECT count(*) as perCount FROM sys_admin WHERE createDate < :date ";
			tcsql = "SELECT count(*) as perCount FROM sys_company WHERE createDate < :date and state='Enable'";
		}
		
		Map<String,String> filter = new HashMap<String,String>();
		filter.put("date", dateS);
		
		//计算统计的日期之前的总数，用于总计的累加
		Long pCount = new Long(0);
		Long cCount = new Long(0);
		List<Map<String, Object>> tmpListMap = jdbcDao.findForListMap(tpsql,filter);
	    if(null != tmpListMap && tmpListMap.size()>0) {
	    	Map lMap = tmpListMap.get(0);
	    	pCount = (Long)lMap.get("perCount");
	    }
	    tmpListMap = jdbcDao.findForListMap(tcsql,filter);
	    if(null != tmpListMap && tmpListMap.size()>0) {
	    	Map lMap = tmpListMap.get(0);
	    	cCount = (Long)lMap.get("perCount");
	    }
	    
		//个人增长情况
		tmpListMap = jdbcDao.findForListMap(psql,filter);
            if(null != tmpListMap && tmpListMap.size()>0) {
	    	for(Map lMap:tmpListMap){
	    		String perDate = (String)lMap.get("perDate");
	    		Long perCount = (Long)lMap.get("perCount");
	    		pmap.put(perDate, perCount);
	    	}
	    }
	    
		//企业增长情况
	    tmpListMap = jdbcDao.findForListMap(csql,filter);
	    if(null != tmpListMap && tmpListMap.size()>0) {
	    	for(Map lMap:tmpListMap){
	    		String perDate = (String)lMap.get("perDate");
	    		Long perCount = (Long)lMap.get("perCount");
	    		cmap.put(perDate, perCount);
	    	}
	    }
	    
	    if(type.equals("month")){
			dateS = DataUtil.DateToString(
                    DataUtil.getAfterDay(curDate, -29), "yyyy-MM-dd");
			
			for ( i = 0; i < 30; i++) {
				String yearMonth = DataUtil.DateToString(
                        DataUtil.getAfterDay(curDate, i - 29), "yyyy-MM-dd");
				
				Long padd = (Long) pmap.get(yearMonth);
				Long cadd = (Long) cmap.get(yearMonth);
				pdata.add(padd);
				cdata.add(cadd);
				
				pCount += padd;
				cCount += cadd;
				tpdata.add(pCount);
				tcdata.add(cCount);
			}
		}else{
			for ( i = 0; i < 12; i++) {
				String yearMonth = DataUtil.DateToString(
                        DataUtil.getAfterMonths(curDate, i - 11), "yyyy-MM");
				
				Long padd = (Long) pmap.get(yearMonth);
				Long cadd = (Long) cmap.get(yearMonth);
				pdata.add(padd);
				cdata.add(cadd);
				
				pCount += padd;
				cCount += cadd;
				tpdata.add(pCount);
				tcdata.add(cCount);
				
			}
		}
	    
		List<JSONObject> dataRows = new ArrayList<JSONObject>();
		//新增客户数，如果有其他则多个yMap到dataRows
		Map<String, Object> yMap = new HashMap<String, Object>();
		yMap.put("name", "用户增长数");
		yMap.put("data", pdata);
		yMap.put("type", "column");
		dataRows.add(JSONObject.fromObject(yMap));
		yMap = new HashMap<String, Object>();
		yMap.put("name", "企业增长数");
		yMap.put("data", cdata);
		yMap.put("type", "column");
		dataRows.add(JSONObject.fromObject(yMap));
		yMap = new HashMap<String, Object>();
		yMap.put("name", "用户累计总数");
		yMap.put("data", tpdata);
		yMap.put("type", "spline");
		yMap.put("yAxis", 1);
		//yAxis: 1,
		dataRows.add(JSONObject.fromObject(yMap));
		yMap = new HashMap<String, Object>();
		yMap.put("name", "企业累计总数");
		yMap.put("data", tcdata);
		yMap.put("type", "spline");
		yMap.put("yAxis", 1);
		dataRows.add(JSONObject.fromObject(yMap));
		
		Map<String, Object> xyMap = new HashMap<String, Object>();
		xyMap.put("d1", dataRows);
		xyMap.put("d2", ndata);
		
		//System.out.println(JSONObject.fromObject(xyMap).toString());
		
		return ajaxJson(JSONObject.fromObject(xyMap).toString());
	}

	public String profile(){
		if(org.apache.commons.lang.StringUtils.isNotEmpty(keyId)){
			user=usersService.get(keyId);
		}
		return "profile";
	}

	public String uploadImg() throws IOException {
		fileManage = gridFSSave(new FileInputStream(filedata), filename,keyId,"APPLICATION/OCTET-STREAM",Users.class);
		fileId=fileManage.getId();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("gridId",fileManage.getId());
		data.put("fileUrl",fileManage.getUrl());
		data.put("status","200");
		data.put("title","操作状态");
		data.put("message","上传头像成功！");

		return ajaxJson(JSONObject.fromObject(data).toString());
	}

	public List<Map<String, String>> getListMap() {
		return listMap;
	}

	public void setListMap(List<Map<String, String>> listMap) {
		this.listMap = listMap;
	}


	public List<Users> getList() {
		return list;
	}


	public void setList(List<Users> list) {
		this.list = list;
	}


	public String getType() {
		return type;
	}


	public void setType(String type) {
		this.type = type;
	}


	public String get_() {
		return _;
	}



	public void set_(String _) {
		this._ = _;
	}


	public String getUsermobile() {
		return usermobile;
	}


	public void setUsermobile(String usermobile) {
		this.usermobile = usermobile;
	}


	public String getName() {
		return name;
	}


	public void setName(String name) {
		this.name = name;
	}


	public String getUsername() {
		return username;
	}


	public void setUsername(String username) {
		this.username = username;
	}

	public Users getUser() {
		return user;
	}

	public void setUser(Users user) {
		this.user = user;
	}

	public String getFiledataContentType() {
		return filedataContentType;
	}

	public void setFiledataContentType(String filedataContentType) {
		this.filedataContentType = filedataContentType;
	}

	public File getFiledata() {
		return filedata;
	}

	public void setFiledata(File filedata) {
		this.filedata = filedata;
	}

	public FileManage getFileManage() {
		return fileManage;
	}

	public void setFileManage(FileManage fileManage) {
		this.fileManage = fileManage;
	}

	public String getFileId() {
		return fileId;
	}

	public void setFileId(String fileId) {
		this.fileId = fileId;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getFiledataFileName() {
		return filedataFileName;
	}

	public void setFiledataFileName(String filedataFileName) {
		this.filedataFileName = filedataFileName;
	}
}
